import moment from 'moment';
import _ from 'lodash';
import { Platform, NativeModules } from 'react-native';
const StringUtil = {
  //'YYYY-MM-DD HH:mm:ss', 'YYYY/MM/DD'
  formatDate(string, oldFormat = 'YYYY-MM-DD HH:mm:ss', format = 'YYYY/MM/DD') {
    if (!string || string.length === 0) {
      return string;
    }
    const s = moment(string, oldFormat).format(format);

    return s.replace('Sunday', '周日')
      .replace('Monday', '周一')
      .replace('Tuesday', '周二')
      .replace('Wednesday', '周三')
      .replace('Thursday', '周四')
      .replace('Friday', '周五')
      .replace('Saturday', '周六')
      ;
  },
  getDurationFromDate(startDate, endDate, format='YYYY-MM-DD HH:mm:ss'){
    const s = moment(startDate, format).toDate().getTime()/1000;
    const e = moment(endDate, format).toDate().getTime()/1000;
    return StringUtil.formatIOSDuration(e-s);
  },
  formatISODate(string, format = 'YYYY/MM/DD') {
    if (!string || string.length === 0) {
      return string;
    }
    const s = moment(string, 'YYYY-MM-DD HH:mm:ss').format(format);

    return s.replace('Sunday', '周日')
        .replace('Monday', '周一')
        .replace('Tuesday', '周二')
        .replace('Wednesday', '周三')
        .replace('Thursday', '周四')
        .replace('Friday', '周五')
        .replace('Saturday', '周六')
        ;
  },
  formatTime(time = 0,duration) {
    const symbol = '';
    time = Math.min(
      Math.max(time, 0),
      duration,
    );

    const formattedMinutes = _.padStart(Math.floor(time / 60).toFixed(0), 2, 0);
    const formattedSeconds = _.padStart(Math.floor(time % 60).toFixed(0), 2, 0);

    return `${symbol}${formattedMinutes}:${formattedSeconds}`;
  },
  formatDuration(duration){
    var theTime = parseInt(duration);// 秒
    var middle= 0;// 分
    var hour= 0;// 小时

    if(theTime >= 60) {
      middle= parseInt(theTime/60);
      theTime = parseInt(theTime%60);
      if(middle>= 60) {
        hour= parseInt(middle/60);
        middle= parseInt(middle%60);
      }
    }
    var result = _.padStart(parseInt(theTime), 2, 0);
    if(middle > 0) {
      result = ""+_.padStart(parseInt(middle), 2, 0)+":"+result;
    }
    else {
      result = ""+_.padStart(0, 2, 0)+":"+result;
    }
    if(hour> 0) {
      result = ""+_.padStart(parseInt(hour), 2, 0)+":"+result;
    }
    else {
      result = ""+_.padStart(0, 2, 0)+":"+result;
    }
    return result;
  },
  formatIOSDuration(duration){
    var theTime = parseInt(duration);// 秒
    var middle= 0;// 分
    var hour= 0;// 小时

    if(theTime >= 60) {
      middle= parseInt(theTime/60);
      theTime = parseInt(theTime%60);
      if(middle>= 60) {
        hour= parseInt(middle/60);
        middle= parseInt(middle%60);
      }
    }
    var result = parseInt(theTime);
    if(middle > 0) {
      result = ""+parseInt(middle)+'分钟'+result+'秒';
    }
    else {
      result = result+'秒';
    }
    if(hour> 0) {
      result = ""+parseInt(hour)+'小时'+result;
    }

    return result;
  },
  getWeek(callback) {
    // 按周日为一周的最后一天计算
    let date = new Date();

    // 今天是这周的第几天
    let today = date.getDay();

    //上周日距离今天的天数（负数表示）
    let stepSunDay = -today + 1;

    // 如果今天是周日
    if (today === 0) {
      stepSunDay = -7;
    }

    // 周一距离今天的天数（负数表示）

    let stepMonday = 7 - today;

    let time = date.getTime();
    let days = [];
    for (let i = 0; i <= stepMonday; ++i) {
      let day = new Date(time + i * 24 * 3600 * 1000);
      days.push(StringUtil.transferDate(day));
    }

    return days;
  },
  transferDate(date) {
    // 年
    const year = date.getFullYear();
    // 月
    let month = date.getMonth() + 1;
    // 日
    let day = date.getDate();

    if (month >= 1 && month <= 9) {

      month = '0' + month;
    }
    if (day >= 0 && day <= 9) {

      day = '0' + day;
    }
    const a = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];

    return year + '-' + month + '-' + day + ` (${a[date.getDay()]})`;
  },
  removeHTMLTag(str) {
    if(!str){
      return '';
    }
    str = str.replace(/<br>/g, '\n');
    str = str.replace(/<br >/g, '\n');
    str = str.replace(/<br\/>/g, '\n');
    str = str.replace(/<w:LsdException[^>]*?>[\s\S]*?<\/w:LsdException>/g, '');
    str = str.replace(/\n+/g, '\n');
    str = str.replace(/<script[^>]*?>[\s\S]*?<\/script>/g, '');
    str = str.replace(/<style[^>]*?>[\s\S]*?<\/style>/g, '');
    str = str.replace(/<\/?[^>]*>/g, ''); //去除HTML tag
    str = str.replace(/[ | ]*\n/g, '\n'); //去除行尾空白
    str = str.replace(/&nbsp;/ig, ' ');//去掉&nbsp;
    return str;
  },
  imagesFromHTML(html) {
    if (!html || html.length === 0) {
      return [];
    }
    const images = [];
    var imgReg = /<img.*?(?:>|\/>)/gi;
    var srcReg = /src=[\'\"]?([^\'\"]*)[\'\"]?/i;
    var arr = html.match(imgReg);  // arr 为包含所有img标签的数组
    if (arr) {
      for (var i = 0; i < arr.length; i++) {
        var src = arr[i].match(srcReg);
        //获取图片地址
        images.push(src[1]);
      }
    }
    return images;

  },
  versionStringCompare(preVersion='', lastVersion=''){
    var sources = preVersion.split('.');
    var dests = lastVersion.split('.');
    var maxL = Math.max(sources.length, dests.length);
    var result = 0;
    for (let i = 0; i < maxL; i++) {
      let preValue = sources.length>i ? sources[i]:0;
      let preNum = isNaN(Number(preValue)) ? preValue.charCodeAt() : Number(preValue);
      let lastValue = dests.length>i ? dests[i]:0;
      let lastNum =  isNaN(Number(lastValue)) ? lastValue.charCodeAt() : Number(lastValue);
      if (preNum < lastNum) {
        result = -1;
        break;
      } else if (preNum > lastNum) {
        result = 1;
        break;
      }
    }
    return result;
  },
  isMiUi12() {
    if (Platform.OS === 'android' && NativeModules.PlatformConstants) {
        const fingerprint = NativeModules.PlatformConstants.Fingerprint && NativeModules.PlatformConstants.Fingerprint.toLowerCase();

        // MiUi12 fingerprint:Xiaomi/cmi/cmi:10/QKQ1.191117.002/V12.0.1.0.QJACNXM:user/release-keys
        if (fingerprint && fingerprint.startsWith('xiaomi') && fingerprint.indexOf('v12') !== -1) {
            return true;
        }
    }

    return false;
  }
};

export default StringUtil;
